package de.hmm.hwip.connection.input;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.Server;
import org.restlet.data.Form;
import org.restlet.data.Protocol;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.restlet.resource.ServerResource;

/** unused class to test an implementation of a rest server. 
 * this could be a solution for webservices 
 * @author johannes mendel
 *
 */
public class RestServerImpl extends ServerResource{
	static Server server = null;
	// Create the HTTP server and listen on port 8182  
	public void start(){
	    try {
			server = new Server(Protocol.HTTP, 8182, RestServerImpl.class);
			server.start();
		} catch (Exception e) {
			System.out.println("exception: " + e.getMessage());
		}  
		 
	}
	
    @Get
    public String respond(){
    	String ret = "Rest ist receives: " +  " Resource URI  : " +  getReference() + '\n' + "Root URI      : "  
                + getRootRef() + '\n' + "Routed part   : "  
                + getReference().getBaseRef() + '\n' + "Remaining part: "  
                + getReference().getRemainingPart() + "\n Request: " + getRequest() + "\n Respsnse: " + getResponse();
		return ret;

    }
    
    @Post
    public String getPost(Representation entity){
    	Form form = new Form(entity);

    	try{
	    	if (entity != null) {

	    		JSONObject json = new JSONObject(form.getValuesMap().toString().substring(1, (form.getValuesMap().toString().length())-6));
	    		
	    		JSONArray nameArray = json.names();
	    		JSONArray valArray = json.toJSONArray(nameArray);
	    		for(int i=0;i<valArray.length();i++)
	    		{
		    		System.out.println("na: " + nameArray);
		    		System.out.println("va: " + valArray);
		    		System.out.println("json nick: " + json.get("nickname"));
	    		}
	    	}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			System.out.println("JSON Exception");
			e.printStackTrace();
		} catch (Exception e){
			System.out.println("JSON -- Exception");
			e.printStackTrace();
		}
    	
    	return "deimudder";
    }
    
    /** stop server **/ 
    public static void stop(){
    	try {
			server.stop();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
